﻿@page "/filedownloads"
@using Microsoft.AspNetCore.Http
@using BlazorBlogs.Data;
@using BlazorBlogs.Data.Models;
@using Microsoft.AspNetCore.Identity;
@inject IHttpContextAccessor httpContextAccessor
@inject UserManager<ApplicationUser> _UserManager
@inject GeneralSettingsService _GeneralSettingsService
@inject BlogsService _BlogsService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject DisqusState DisqusState
@inherits OwningComponentBase

<h1>Downloads</h1>
@if (!UserIsLoggiedIn)
{
    <p>You must be logged in to download files</p>
    @if (AllowRegistration)
    {
        <a href="Identity/Account/Login">[Login]</a>
    }
}
@if (UserIsAnAdmin)
{
    <button type="button" class="btn btn-link oi oi-cloud-upload" @onclick="(() => UploadFile())"> Upload</button>
}
<hr />

@if (colFiles.FilesCount == 0)
{
    <h2>No items returned</h2>
}
else
{
    @foreach (var file in colFiles.Files)
    {
        @if (UserIsAnAdmin)
        {
            <button type="button" class="btn btn-link" @onclick="(() => EditFile(file))">[Edit]</button>
        }
        @if (UserIsLoggiedIn)
        {
            <button class="btn btn-link oi oi-cloud-download" @onclick="@(() => DownloadFile(file))"> @file.FileName</button>
        }
        else
        {
            <span class="oi oi-cloud-download"> @file.FileName</span>
        }
        <br />
    }
    <br />
}
@if (ShowPreviousButton)
{
    <button class="btn btn-warning"
            @onclick="Previous">
        <b>&#x3C;</b>
    </button>
}
@if (ShowNextButton)
{
    <button class="btn btn-warning"
            @onclick="Next">
        <b>&#x3E;</b>
    </button>
}

@if (FileUploadPopup)
{
    <div class="modal" tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Upload File</h3>
                    <!-- Button to close the popup -->
                    <button type="button" class="close"
                            @onclick="CloseUploadPopup">
                        <span aria-hidden="true">X</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h5>File Name</h5>
                    <div class="form-group">
                        <input class="form-control" type="text"
                               @bind="SelectedFile.FileName" />
                    </div>
                    <RadzenUpload ChooseText="Upload And Save" Multiple="false"
                                  Accept="application/x-zip-compressed"
                                  Url=@($"api/upload/single?FileTitle={SelectedFile.FileName}")
                                  Style="margin-bottom: 20px;height: 45px"
                                  Progress="@((args) => OnProgress(args))" />
                </div>
            </div>
        </div>
    </div>
}

@if (FileEditPopup)
{
    <div class="modal" tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Edit File</h3>
                    <!-- Button to close the popup -->
                    <button type="button" class="close"
                            @onclick="ClosePopup">
                        <span aria-hidden="true">X</span>
                    </button>
                </div>
                <div class="modal-body">
                    <h5>File Name</h5>
                    <div class="form-group">
                        <input class="form-control" type="text"
                               @bind="SelectedFile.FileName" />
                    </div>
                    <div class="modal-body">
                        <button class="btn btn-primary"
                                @onclick="SaveFile">
                            Save
                        </button>
                        <button class="btn btn-danger"
                                @onclick="DeleteFile">
                            Delete
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@if (ConfirmDeletePopup)
{
    <div class="modal" tabindex="-1" style="display:block;background-color:gainsboro" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Delete File?</h3>
                </div>
                <div class="modal-body">
                    <button class="btn btn-primary"
                            @onclick="DeleteYes">
                        Yes
                    </button>
                    <button class="btn btn-danger"
                            @onclick="DeleteNo">
                        No
                    </button>
                </div>
            </div>
        </div>
    </div>
}

@if (ShowProgressBarPopup)
{
    <div class="modal" tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Upload Status</h4>
                </div>
                <div align="center">
                    <RadzenProgressBar Value="@progress"
                                       Unit="@info"
                                       Visible="@(progress > 0)"
                                       Style="margin-bottom: 20px" />
                </div>
            </div>
        </div>
    </div>
}

@code {

    [CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }

    string ADMINISTRATION_ROLE = "Administrators";
    bool UserIsAnAdmin = false;
    bool UserIsLoggiedIn = false;

    public bool FileUploadPopup = false;
    public bool FileEditPopup = false;
    public bool ConfirmDeletePopup = false;
    private bool ShowProgressBarPopup = false;
    private int progress;
    private string info;
    GeneralSettings objGeneralSettings = new GeneralSettings();
    bool AllowRegistration = false;
    System.Security.Claims.ClaimsPrincipal CurrentUser;
    FilesDTO SelectedFile = new FilesDTO();
    private int CurrentPage = 1;

    FilesPaged colFiles =
    new FilesPaged()
    {
        Files = new List<FilesDTO>(),
        FilesCount = 0
    };

    bool ShowPreviousButton
    {
        get
        {
            return (CurrentPage > 1);
        }
    }

    bool ShowNextButton
    {
        get
        {
            return (
                (colFiles.FilesCount > (CurrentPage * 10))
                );
        }
    }

    protected override async Task OnInitializedAsync()
    {
        // Get the current logged in user
        CurrentUser = (await authenticationStateTask).User;

        if (CurrentUser != null)
        {
            UserIsLoggiedIn = CurrentUser.Identity.IsAuthenticated;
            UserIsAnAdmin = CurrentUser.IsInRole(ADMINISTRATION_ROLE);
        }

        _GeneralSettingsService = (GeneralSettingsService)ScopedServices.GetService(typeof(GeneralSettingsService));
        _BlogsService = (BlogsService)ScopedServices.GetService(typeof(BlogsService));

        await LoadGeneralSettingsAsync();

        // Get the users
        await GetFiles();

        DisqusState.SetDisplayDisqus(false);
    }

    protected async Task LoadGeneralSettingsAsync()
    {
        objGeneralSettings = await _GeneralSettingsService.GetGeneralSettingsAsync();
        AllowRegistration = objGeneralSettings.AllowRegistration;
    }

    public async Task GetFiles()
    {
        colFiles = await _BlogsService.GetFilesAsync(CurrentPage);
    }

    // File

    void UploadFile()
    {
        SelectedFile = new FilesDTO();
        SelectedFile.FileName = "";
        FileUploadPopup = true;
    }

    void CloseUploadPopup()
    {
        FileUploadPopup = false;
    }

    void EditFile(FilesDTO paramFile)
    {
        SelectedFile = paramFile;
        FileEditPopup = true;
    }

    async Task SaveFile()
    {
        await _BlogsService.UpdateFilesAsync(SelectedFile);

        // Refresh collection
        colFiles = await _BlogsService.GetFilesAsync(CurrentPage);

        // Close popup
        FileEditPopup = false;
    }

    void DeleteFile()
    {
        ConfirmDeletePopup = true;
    }

    void DeleteNo()
    {
        ConfirmDeletePopup = false;
    }

    void ClosePopup()
    {
        FileEditPopup = false;
    }

    async Task DeleteYes()
    {
        // Delete File
        await _BlogsService.DeleteFilesAsync(SelectedFile);

        // Log
        await LogAction($"{CurrentUser.Identity.Name} deleted file {SelectedFile.FilePath}");

        // Refresh collection
        colFiles = await _BlogsService.GetFilesAsync(CurrentPage);

        // Close popup
        ConfirmDeletePopup = false;
        FileEditPopup = false;
    }

    // Download File

    async Task DownloadFile(FilesDTO paramFile)
    {
        // Log
        await LogAction($"Download File #{paramFile.FilePath}");

        // Update Download count
        paramFile.DownloadCount = (paramFile.DownloadCount + 1);
        await _BlogsService.UpdateFilesAsync(paramFile);

        // Download file
        NavigationManager.NavigateTo($"api/File/DownloadFile?FileName={paramFile.FilePath}", true);
    }

    // Upload File

    private void OnProgress(UploadProgressArgs args)
    {
        ShowProgressBarPopup = true;
        this.info = $"{args.Loaded} of {args.Total} bytes.";
        this.progress = args.Progress;

        StateHasChanged();

        if (args.Loaded == args.Total)
        {
            ShowProgressBarPopup = false;
            FileUploadPopup = false;

            NavigationManager.NavigateTo("FileDownloads", true);
        }
    }

    // Paging

    async Task Previous()
    {
        if (CurrentPage > 1)
        {
            CurrentPage = CurrentPage - 1;
            colFiles = await _BlogsService.GetFilesAsync(CurrentPage);
        }
    }

    async Task Next()
    {
        CurrentPage = CurrentPage + 1;
        colFiles = await _BlogsService.GetFilesAsync(CurrentPage);
    }

    // Logging

    private async Task LogAction(string strAction)
    {
        // Get the current user
        var CurrentUser = (await authenticationStateTask).User;

        BlazorBlogs.Data.Models.Logs objLog = new BlazorBlogs.Data.Models.Logs();
        objLog.LogDate = DateTime.Now;
        objLog.LogAction = strAction;
        objLog.LogUserName = (CurrentUser.Identity.Name != null) ? CurrentUser.Identity.Name : "";
        try
        {
            objLog.LogIpaddress = httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();
        }
        catch
        {
            objLog.LogIpaddress = "127.0.0.1";
        }

        var result = await _BlogsService.CreateLogAsync(objLog);
    }
}
